package vn.cuhanh.fragment;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vn.cuhanh.ChooseGameActivity;
import vn.cuhanh.GameDetailActivity;
import vn.cuhanh.NewsDetailActivity;
import vn.cuhanh.R;
import vn.cuhanh.adapter.NewHomeListAdapter;
import vn.cuhanh.bean.Banner;
import vn.cuhanh.bean.RssItem;
import vn.cuhanh.customview.HorizontalListView;
import vn.cuhanh.models.Model_News;
import vn.cuhanh.utils.HelperFunc;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class NewsFragment extends BasicFragment {
	
	private static String GA_CATEGORY = "news_fragment";
	private ArrayList<Banner> topBannersUrl = null;
	private static HorizontalListView viewpagerTopBanner;
	private View view;
	private final String TAB_NEWS = "news";
	private final String TAB_TOURNAMENT = "tournament";
	private final String TAB_EVENT = "event";
	private final String TAB_COMMUNITY = "community";
	private final String[] TABS = new String[]{TAB_NEWS, TAB_TOURNAMENT, TAB_EVENT, TAB_COMMUNITY};
	private final int[] TAB_IDS = new int[]{R.id.news_tab_news, R.id.news_tab_tournament, R.id.news_tab_event, R.id.news_tab_community};
	private final int[] TAB_CONTROLL_IDS = new int[] {R.id.news_tabcontroll_news, R.id.news_tabcontroll_tournament, R.id.news_tabcontroll_event, R.id.news_tabcontroll_community};
	private final int[] CATEGORY_IDS = new int[] {1, 4, 2, 3};
	private final boolean[] isLoadingNews = new boolean[]{false, false, false, false};
	private int mCurrentTab = 0;
	private View noNetworkScreen;
	private LinearLayout contentWrapper;
	private boolean firstLoad = true;
	private View loading;
	
	private ArrayList<ArrayList<RssItem>> lists = new ArrayList<ArrayList<RssItem>>();
	private RSSListAdaptor[] adapters = new RSSListAdaptor[4];
	private PullToRefreshListView[] tabs = new PullToRefreshListView[4];
	private int[] currentPages = new int[]{0,0,0,0};
	private TextView[] tabControlls = new TextView[4];
	
	public static NewsFragment newInstance(Context ctx) {
		return new NewsFragment(ctx);
	}

	public NewsFragment(Context ctx) {
		super(ctx);
		for(int i = 0; i < 4; i++) {
			lists.add(new ArrayList<RssItem>());
			adapters[i] = new RSSListAdaptor(ctx, R.id.news_list, i);
		}
	}

	public NewsFragment() {
		super(GameDetailActivity.gameDetailContext);
		if(ctx != null) {
			for(int i = 0; i < 4; i++) {
				lists.add(new ArrayList<RssItem>());
				try {
					adapters[i] = new RSSListAdaptor(ctx, R.id.news_list, i);
				} catch(Exception e) {
					HelperFunc.readStackTrace(e);
				}
			}
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// setUserVisibleHint(true);
	}

	@Override
	public void onPause() {
		super.onPause();
		// HelperFunc.unbindDrawables(view);
		// System.gc();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	public void showNoData() {
		contentWrapper.setVisibility(View.GONE);
		noNetworkScreen.setVisibility(View.VISIBLE);
	}
	
	public void loadData() {
//		getBanner();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		try {
			view = inflater.inflate(R.layout.news, null);
			if (ctx == null || view == null) {
				if (isAdded()) {
					ctx = getActivity();
				} else {
					return view;
				}
			}
			// manually start loading stuff in the first tab
			initNoDataScreen();
			initTabControll();
			initTabs(); 
			getBanner();
			return view;
		} catch (InflateException e) {
			HelperFunc.readStackTrace(e);
		} catch (Exception e) {
			HelperFunc.readStackTrace(e);
		}
		return null;
	}
	
	public void initTabControll() {
		if(view == null) {
			return;
		}
		for(int i = 0; i < 4; i++) {
			OnTabControllClickHandler onClickHandler = new OnTabControllClickHandler();
			tabControlls[i] = (TextView) view.findViewById(TAB_CONTROLL_IDS[i]);
			tabControlls[i].setOnClickListener(onClickHandler);
		}
	}
	public void setTabActive(View v) {
		v.setBackgroundColor(0xFFFFFFFF);
		View parent = (View)v.getParent();
		parent.setBackgroundColor(0xFFFFFFFF);
	}
	
	public void setTabInActive(View v) {
		v.setBackgroundResource(R.drawable.tab_controll_textview_background);
		View parent = (View)v.getParent();
		parent.setBackgroundColor(0xFF9D9D9D);
	}
	
	public void showTab(final int index) {
		for(int i = 0; i < 4; i++) {
			if(i == index) {
				setTabActive(tabControlls[i]);
			} else {
				setTabInActive(tabControlls[i]);
			}
		}
		for(int i = 0; i < 4; i++) {
			if(index == i) {
				tabs[i].setVisibility(View.VISIBLE);
			} else {
				tabs[i].setVisibility(View.GONE);
			}
		}
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				loadNews(index, 1);
			}
		}, 1000);
	}
	
	public class OnTabControllClickHandler implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(v == null) {
				HelperFunc.trackEvent(ctx, GA_CATEGORY, "tab_press", "");
				return;
			}
			mCurrentTab = HelperFunc.indexOfIntArray(TAB_CONTROLL_IDS, v.getId());
			HelperFunc.trackEvent(ctx, GA_CATEGORY, "tab_press", "" + mCurrentTab);
			
			showTab(mCurrentTab);
		}
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void initTabs() {
		for(int i = 0; i < 4; i++) {
			tabs[i] = (PullToRefreshListView) view.findViewById(TAB_IDS[i]);
			tabs[i].setAdapter(adapters[i]);
			final int finalIndex = i;
			tabs[i].setMode(Mode.BOTH);
			tabs[i].setOnRefreshListener(new OnRefreshListener2() {
				@Override
				public void onPullDownToRefresh(PullToRefreshBase refreshView) {
					// TODO Auto-generated method stub
					loadNews(finalIndex, 0);
				}

				@Override
				public void onPullUpToRefresh(PullToRefreshBase refreshView) {
					// TODO Auto-generated method stub
					loadNews(finalIndex, currentPages[finalIndex] + 1);
				}
			});
		}
		showTab(mCurrentTab);
	}
	
	public void initNoDataScreen() {
		contentWrapper = (LinearLayout)view.findViewById(R.id.news_content_wrapper);
		noNetworkScreen = view.findViewById(R.id.news_no_network);
		noNetworkScreen.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				loadData();
			}
		});
//		loading = view.findViewById(R.id.loading_image);
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	/**
	 * Append a list of rssItem into the end of the list has index "tabIndex", duplicate item will be ignored.
	 * @param tabIndex
	 * @param tmpList
	 */
	public void appendNewsToEnd(int tabIndex, ArrayList<RssItem> tmpList) {
		RssItem currentLastItem = null;
		if(lists.get(tabIndex) != null && !lists.get(tabIndex).isEmpty()) {
			currentLastItem = lists.get(tabIndex).get(lists.get(tabIndex).size() - 1);
		}
		for(int i = 0; i < tmpList.size(); i++) {
			RssItem tmp = tmpList.get(i);
			if(currentLastItem != null && currentLastItem.getId() <= tmp.getId()) {
				continue;
			}
			lists.get(tabIndex).add(tmp);
		}
	}
	/**
	 * Insert a list of rssItem into the top of the list has index "tabIndex", duplicate item will be ignored.
	 * @param tabIndex
	 * @param tmpList
	 */
	public void insertNewsToTop(final int tabIndex, ArrayList<RssItem> tmpList) {
		RssItem firstItem = null;
		if(lists.get(tabIndex).size() > 0) {
			firstItem = lists.get(tabIndex).get(0);
		}
		for(int i = tmpList.size() - 1; i >= 0; i--) {
			RssItem tmp = tmpList.get(i);
			if(firstItem != null && firstItem.getId() >= tmp.getId()) {
				continue;
			}
			firstItem = tmp;
			lists.get(tabIndex).add(0, tmp);
		}
	}
	
	/**
	 * Load news from server and udpate to listView
	 * @param tabIndex
	 * @param page (0: refresh, >=1: load page) 
	 */
	public void loadNews(final int tabIndex, final int page) {
		if(isLoadingNews[tabIndex]) {
			return;
		}
		if(page <= currentPages[tabIndex] && page != 0) {
			((Activity)ctx).runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					adapters[tabIndex].notifyDataSetChanged();
				}
			});
			return;
		}
		isLoadingNews[tabIndex] = true;
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				ArrayList<RssItem> tmpList = Model_News.retrieveRSSFeed(ctx, ChooseGameActivity.current.getId(), CATEGORY_IDS[tabIndex], page);
				isLoadingNews[tabIndex] = false;
				if(tabs[tabIndex] != null) {
					((Activity)ctx).runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							tabs[tabIndex].onRefreshComplete();
						}
					});
				}
				if(tmpList == null) {
					return;
				}
				if(page != 0) {
					currentPages[tabIndex] = page;
					appendNewsToEnd(tabIndex, tmpList);
				} else {
					insertNewsToTop(tabIndex, tmpList);
				}
				((Activity)ctx).runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						adapters[tabIndex].notifyDataSetChanged();
					}
				});
			}
		});
		thread.start();
	}
	
	public void getBanner() {
		getBanner(false);
	}
	
	public void getBanner(boolean forced) {
		if(topBannersUrl != null && !forced) {
			initTopBannerList();
			return;
		}
		BannerLoader loaderTopBanner = new BannerLoader();
		loaderTopBanner.execute(ctx);
	}
	
	public void initTopBannerList() {
		try {
			viewpagerTopBanner = (HorizontalListView) view.findViewById(R.id.news_top_banner);
			NewHomeListAdapter adapter = new NewHomeListAdapter(ctx, topBannersUrl);
			viewpagerTopBanner.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					// TODO Auto-generated method stub
					HelperFunc.trackEvent(ctx, GA_CATEGORY, "banner_press", "News_top_banner", (long)position);
					if(position >= topBannersUrl.size()) {
						return;
					}
					Banner clickedBanner  = topBannersUrl.get(position);
					Log.d("News fragment top banner click", clickedBanner.getNewsId() + "");
					if(clickedBanner.getNewsId() == 0) {
						if(clickedBanner.getLink() != null && !clickedBanner.getLink().trim().isEmpty()) {
							Intent intent = new Intent(ctx, NewsDetailActivity.class);
							intent.putExtra("type", NewsDetailActivity.TYPE_URL);
							intent.putExtra("content", clickedBanner.getLink());
							ctx.startActivity(intent);
						}
						return;
					}
					Model_News.showNewsContent(ctx, clickedBanner.getNewsId());
				}
			});
			if(adapter.getItemWidth() == 0) {
				adapter.setItemWidth(viewpagerTopBanner.getMeasuredWidth());
				adapter.setItemHeight(viewpagerTopBanner.getMeasuredHeight());
			}
			viewpagerTopBanner.setAdapter(adapter);
			adapter.notifyDataSetChanged();
//			viewpagerTopBanner.setCurrentItem(0);
		} catch (NullPointerException e) {
			HelperFunc.readStackTrace(e);
		}
		
//		 indicator.setViewPager(viewpagerTopBanner);
//		 setOnClickBanner();
	}
	
	private class BannerLoader extends
			AsyncTask<Context, Integer, ArrayList<Banner>> {
		@Override
		protected ArrayList<Banner> doInBackground(Context... params) {
			Context ctx = params[0];

			int Measuredwidth = 0;
			int Measuredheight = 0;

			WindowManager w = ((Activity) ctx).getWindowManager();

			Display d = w.getDefaultDisplay();
			Measuredwidth = d.getWidth();
			Measuredheight = d.getHeight();

			String bannerUrl = ctx.getResources().getString(R.string.bannerUrlTop);
			bannerUrl = bannerUrl + "&heigth=" + Measuredheight + "&width="
					+ Measuredwidth;
			String str = HelperFunc.getDataFromSv(bannerUrl);

			ArrayList<Banner> urls = null;
			if (str != null) {
				try {
					JSONArray banners;
					banners = new JSONArray(str);
					urls = new ArrayList<Banner>();
					for (int i = 0; i < banners.length(); i++) {
						JSONObject banner = banners.getJSONObject(i);
						Banner temp = new Banner(banner.getString("name"),
								(int) banner.getInt("id"),
								banner.getString("link"),
								banner.getString("urlImage"),
								banner.getString("des"),
								(banner.isNull("newsId") ? 0 : banner.getInt("newsId")));

						urls.add(temp);
					}
				} catch (JSONException e) {

					e.printStackTrace();
				}
			}
			return urls;
		}

		@Override
		protected void onPostExecute(ArrayList<Banner> result) {
			if (isAdded() && result != null) {
				topBannersUrl = result;
				initTopBannerList();
			}
			super.onPostExecute(result);
		}
	}

	private class RSSListAdaptor extends ArrayAdapter<RssItem> {

		private int index;
		public RSSListAdaptor(Context context, int textviewid, int index) {
			super(context, textviewid);
			this.index = index;
		}

		@Override
		public int getCount() {
			return ((null != lists.get(index)) ? lists.get(index).size() : 0);
		}

		@Override
		public RssItem getItem(int position) {
			return ((null != lists.get(index)) ? lists.get(index).get(position) : null);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View rssListItemView = convertView;

			if (null == rssListItemView) {
				LayoutInflater vi = (LayoutInflater) NewsFragment.this.ctx
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				rssListItemView = vi.inflate(R.layout.rss_item, null);
			}

			final RssItem data = getItem(position);

			if (null != data) {
				TextView title = (TextView) rssListItemView.findViewById(R.id.rss_item_title);
				TextView date = (TextView) rssListItemView.findViewById(R.id.rss_item_date);
				title.setText(data.getTitle());
				date.setText(data.getDate());
				
				title.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						HelperFunc.trackEvent(ctx, GA_CATEGORY, "news_item_press", "News_item_press");
						Model_News.showNewsContent(ctx, data.getId());
					}
				});
			}

			return rssListItemView;
		}
	}
}
